package com.snts.synchronization.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.snts.synchronization.garbage.Utils;

public class SessionManagerImpl implements SessionManager {

	private HashMap<String, Session> currentSessions = new HashMap<String, Session>(1000);
	private long sessionTimeout = 10 * 60 * 1000;
	private long testInterval = 15 * 1000;
	private long lastTest = 0;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.snts.synchronization.server.SessionManager#createSession()
	 */
	@Override
	public Session createSession() {
		testSessions();
		String sessionId = null;
		while (currentSessions.containsKey(sessionId = Utils.generateSessionId())) {
		}
		Session session = new Session(sessionId);
		currentSessions.put(sessionId, session);
		return session;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.snts.synchronization.server.SessionManager#getSession(java.lang.String
	 * )
	 */
	@Override
	public Session getSession(String sessionId) {
		testSessions();
		Session session = currentSessions.get(sessionId);
		if (session != null && (new Date().getTime() - session.time) > sessionTimeout) {
			currentSessions.remove(sessionId);
			return null;
		}
		return session;
	}

	private void testSessions() {
		if (new Date().getTime() - lastTest > testInterval) {
			ArrayList<String> sessionsToDelete = new ArrayList<String>();
			for (Map.Entry<String, Session> entry : currentSessions.entrySet()) {
				if ((new Date().getTime() - entry.getValue().time) > sessionTimeout) {
					sessionsToDelete.add(entry.getKey());
				}
			}
			for (String sessionId : sessionsToDelete) {
				currentSessions.remove(sessionId);
			}
		}
	}

}
